var native_http = require("@native.http");
var native_fs = require("@native.fs");
var sys = require("@native.builtin");
var fs = require("fs.js");

function request(options){
    var method = options.method;
    if (method == undefined) {
        method = "GET";
    }
    if (options.url == undefined || options.url == "") {
        return undefined;
    }
    var resp_header = options.headers;
    var data = options.data;
    if (data == undefined || data == null) data = ""
    var timeout = options.timeout;
    if(timeout == undefined)
        timeout = 10000;

    var str_header = "";
    for(var i = 0; i < resp_header.length; i++) {
        str_header += resp_header[i] + "\r\n";
    }
    str_header += "\r\n";

    var resp = native_http.createResponseBuffer();
    if (resp == null) {
        return undefined;
    }
    // console.log("response 1 =====> ")
    // console.log(resp)
    // console.log(" <=====")

    var status_code = native_http.request(options.url, method, str_header, data, timeout, resp);
    var response = native_http.getResponse(resp);

    console.log("response 2 =====> ")
    console.log(resp)
    console.log(response)
    console.log(" <=====")

    var length = native_http.getResponseLength(resp);
    // console.log("length =====> ")
    // console.log(length)
    // console.log(" <=====")
    // var buffer = sys.toJsString(response, length);
    // console.log("data type parse");
    // console.log(buffer)
    // console.log("//////////////////////")

    if (options.callback == undefined || options.callback == null || typeof(options.callback) != "function") {
        return undefined;
    }

    if (options.error == undefined || options.error == null || typeof(options.error) != "function") {
        return undefined;
    }

    var header = native_http.getHeader();
    var header_length = native_http.getHeaderLength();
    var header_str = sys.toJsString(header, header_length);

    var result = {
        statusCode: status_code,
        data: null,
        headers: header_str,
    }

    if (options.responseType) {
        if (options.responseType == "file" && options.fileName) {
            var fd = native_fs.open(options.fileName, "w+");
            native_fs.write(fd, response, length);
            // fs.writeFile(options.fileName, response, "w+")
            result.data = length;
        } else {
            result.data = sys.toJsString(response, length);
        }
    } else {
        result.data = sys.toJsString(response, length);
    }

    if (status_code >= 200 && status_code <= 300) {
        options.callback(result)
    } else {
        options.error(result)
    }

    native_http.freeResponseBuffer(resp);
}
